import { NameSpace } from 'utils';
import exceed from 'utils/apimap';
import { Message } from '@teamix/ui';
import intl from '../../../../../../../../../locale';

const { organization_id: org_id, id } = window.FORCE.organization;

const ns = NameSpace('risk-manage');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RECEIVE_SETTING_DATA = ns('RECEIVE_SETTING_DATA');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

// 敏感信息报表-查询概要信息
export function getInfoReportOverview() {
  return (dispatch) => {
    updateData({
      infoReportOverviewLoading: true,
    })(dispatch);

    const overviewPromise = exceed.forceFetch({
      api: 'organization.sensitive.info_report.overview',
      params: {
        org_id: id,
      },
    });

    const repoCountPromise = exceed.forceFetch({
      api: 'organization.sensitive.info_report.overview.count',
      params: {
        org_id,
      },

      data: {
        integration_service: 'sensitive_info_detection',
      },
    });

    Promise.all([overviewPromise, repoCountPromise]).then((res) => {
      const result = res && res[0] ? res[0] : {};
      const repoCountInfo = res && res[1] ? res[1] : {};
      if (result) {
        result.enabled_project_num = repoCountInfo.isOpenCount || 0;
        result.disabled_project_num = repoCountInfo.isNotOpenCount || 0;
      }
      updateData({
        infoReportOverview: result,
        infoReportOverviewLoading: false,
      })(dispatch);
    });
  };
}

// 安全通知设置查询
export function getSecuritySettingData() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'organization.security.setting.get',
        params: {
          id,
        },
      })
      .then((result) => {
        // 获取通知设置
        const { notify_method } = result.list.find((val) => val.name === 'SENSITIVE_OP');
        updateData({
          notify_method,
        })(dispatch);
      });
  };
}

// 获取开关设置
export function getSensitiveSetting() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'organization.repo.setting.get',
        params: {
          org_id: id,
        },
      })
      .then((result) => {
        const { is_sensitive_behavior_enable } = result;
        updateData({
          is_sensitive_behavior_enable,
          getSensitiveSettingEnd: true,
        })(dispatch);
      });
  };
}

// 更新敏感信息检测开关
export function updateSensitiveSetting(data, cb) {
  return (dispatch, getState) => {
    // FIXME 后期loading-switch加好后，去除
    const { is_sensitive_behavior_enable: oldValue } = getState().organization.settings.risk;
    updateData(data)(dispatch);
    exceed
      .forceFetch({
        api: 'organization.repo.setting.post',
        params: {
          id,
        },

        data,
      })
      .then(
        () => {
          if (data.is_sensitive_behavior_enable) {
            Message.success({
              title: intl.get({
                id: 'code-assets.risk.actions.Enabled',
                defaultMessage: '开启成功',
              }),
            });
          } else {
            Message.success({
              title: intl.get({
                id: 'code-assets.risk.actions.ClosedSuccessfully',
                defaultMessage: '关闭成功',
              }),
            });
          }

          updateData(data)(dispatch);
          cb && cb();
        },
        () => {
          Message.error({
            title: intl.get({
              id: 'code-assets.risk.actions.FailedToModify',
              defaultMessage: '修改失败',
            }),
          });

          updateData({
            is_sensitive_behavior_enable: oldValue,
          })(dispatch);
          cb && cb();
        },
      );
  };
}

// 获取敏感信息服务设置
export function getOrgServiceSetting() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'org.service.get',
        params: {
          orgId: org_id,
        },
      })
      .then((result) => {
        updateData({
          sensitive_info_detection: result.sensitive_info_detection,
          project_report: result.project_report,
        })(dispatch);
      });
  };
}

// 开启服务
export function openService(cb) {
  return (dispatch, getState) => {
    const { isOpeningService } = getState().organization.settings.risk;
    if (isOpeningService) {
      return;
    }
    updateData({
      isOpeningService: true,
    })(dispatch);
    exceed
      .fetch({
        api: 'org.service.open',
        params: {
          orgId: org_id,
        },

        data: {
          integration_service: 'sensitive_info_detection',
        },
      })
      .then((result) => {
        updateData({
          sensitive_info_detection: result.sensitive_info_detection,
          isOpeningService: false,
        })(dispatch);
        cb && cb();
      })
      .fail(() => {
        updateData({
          isOpeningService: false,
        })(dispatch);
      });
  };
}

// 关闭服务
export function closeService() {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'org.service.close',
        params: {
          orgId: org_id,
        },

        data: {
          integration_service: 'sensitive_info_detection',
        },
      })
      .then(() => {
        updateData({
          sensitive_info_detection: {
            enabled: false,
          },
        })(dispatch);
      });
  };
}

// 更新服务
export function updateService({ forced_control }) {
  return (dispatch, getState) => {
    const { project_report } = getState().organization.settings.risk;
    exceed
      .forceFetch({
        api: 'org.service.update',
        params: {
          orgId: org_id,
        },

        data: {
          sensitive_info_detection: {
            enabled: true,
            forced_control,
          },

          project_report,
        },
      })
      .then((result) => {
        updateData({
          sensitive_info_detection: result.sensitive_info_detection,
        })(dispatch);
        // 更新后刷新页面
        // window.location.reload();
        Message.success('更新成功');
      });
  };
}

// 批量开启
export function batchOpenService(repoIds, cb) {
  return (dispatch, getState) => {
    const { isBatchOpening } = getState().organization.settings.risk;
    if (isBatchOpening) {
      return;
    }
    updateData({
      isBatchOpening: true,
    })(dispatch);
    exceed
      .fetch({
        api: 'org.service.batchopen',
        params: {
          orgId: org_id,
          integration_service: 'sensitive_info_detection',
        },

        data: {
          projectIdList: repoIds,
        },
      })
      .then(() => {
        updateData({
          isBatchOpening: false,
        })(dispatch);
        cb && cb();
      })
      .fail((err) => {
        console.error(err);
        updateData({
          isBatchOpening: false,
        })(dispatch);
      });
  };
}

function transformExceedToPromise(api = '', params = {}, data = {}) {
  return new Promise((resolve, reject) => {
    exceed
      .fetch({
        api,
        params,
        data,
      })
      .then((result) => {
        resolve(result);
      })
      .fail(() => {
        reject();
      });
  });
}

let timer = null;
let isRefreshing = false;
let refreshMessageExist = false;
export function getOverviewScore(needLoading = true) {
  return (dispatch) => {
    if (needLoading) {
      dispatch(
        updateData({
          isLoadingScore: true,
        }),
      );
    }

    const repo_setting_req = transformExceedToPromise('organization.repo.setting.get', {
      org_id: id,
    });

    const score_req = transformExceedToPromise('org.risk.overview.score.get', {
      org_id: id,
    });

    // 获取白名单
    const sensitive_whitelist_req = transformExceedToPromise(
      'organization.grant_behavior.list',
      {
        orgId: id,
      },
      {
        users: '',
        operation_types: '',
        page: 1,
        per_page: 10,
      },
    );

    // 获取敏感信息通知设置
    const sensitive_notify_req = transformExceedToPromise('organization.security.setting.get', {
      id,
    });

    Promise.all([score_req, repo_setting_req, sensitive_whitelist_req, sensitive_notify_req])
      .then((res) => {
        const [result = {}, repoSetting, sensitive_whitelist_result, sensitive_notify_result] = res;
        const scoreInfo = { ...result };

        scoreInfo.is_sensitive_behavior_enable =
          repoSetting && repoSetting.is_sensitive_behavior_enable;

        // 禁止强制推送或代码属主检查
        scoreInfo.is_commit_check_ok = false;
        if (repoSetting) {
          scoreInfo.is_commit_check_ok =
            !!(
              repoSetting.repo_push_author_forge_check ||
              repoSetting.repo_push_committer_forge_check
            ) || repoSetting.is_force_push_forbidden;
        }

        // 默认为true
        scoreInfo.is_sensitive_behavior_enable_with_notify = true;
        scoreInfo.is_sensitive_behavior_enable_without_whitelist = true;
        if (scoreInfo.is_sensitive_behavior_enable) {
          if (sensitive_whitelist_result[0] && sensitive_whitelist_result[0].amount === 0) {
            scoreInfo.is_sensitive_behavior_enable_without_whitelist = true;
          } else {
            scoreInfo.is_sensitive_behavior_enable_without_whitelist = false;
          }

          if (sensitive_notify_result) {
            const { notify_method } =
              sensitive_notify_result.find((val) => val.name === 'SENSITIVE_OP') || {};
            // EMAIL,IN_SITE 当前只有2种
            const sensitive_notify_method = ['EMAIL', 'IN_SITE'];
            if (
              notify_method === sensitive_notify_method.join() ||
              notify_method === sensitive_notify_method.reverse().join()
            ) {
              scoreInfo.is_sensitive_behavior_enable_with_notify = true;
            } else {
              scoreInfo.is_sensitive_behavior_enable_with_notify = false;
            }
          }
        }

        scoreInfo.is_issue_rate_ok =
          scoreInfo.organizationSecurityScoreDo &&
          scoreInfo.organizationSecurityScoreDo.issueRate === 0;
        scoreInfo.is_service_rate_ok =
          scoreInfo.organizationSecurityScoreDo &&
          scoreInfo.organizationSecurityScoreDo.integrationServiceRate === 100;
        scoreInfo.is_branch_ok =
          scoreInfo.isPushRulerOpen &&
          scoreInfo.organizationSecurityScoreDo &&
          scoreInfo.organizationSecurityScoreDo.protectBranchRate === 100;

        dispatch(
          updateData({
            isLoadingScore: false,
            scoreInfo,
          }),
        );

        // 如果是running，定时查询
        if (
          scoreInfo.organizationSecurityScoreDo &&
          scoreInfo.organizationSecurityScoreDo.state === 'running'
        ) {
          isRefreshing = true;
          if (isRefreshing && !refreshMessageExist) {
            refreshMessageExist = true;
          }
          timer = setTimeout(() => {
            dispatch(getOverviewScore(false));
          }, 1000);
        } else {
          clearTimeout(timer);
          if (isRefreshing && refreshMessageExist) {
            isRefreshing = false;
            refreshMessageExist = false;
            // Message.closeAll();
            Message.success({
              title: intl.get({
                id: 'code-assets.risk.actions.SecurityScoreRefreshed',
                defaultMessage: '安全评分已刷新',
              }),
            });
          }
        }
      })
      .catch((err) => {
        console.error(err);
        dispatch(
          updateData({
            isLoadingScore: false,
          }),
        );
      });
  };
}

export function getAllCount() {
  return (dispatch) => {
    dispatch(
      updateData({
        isLoadingOverviewCount: true,
      }),
    );

    const operate_req = transformExceedToPromise('org.risk.overview.operation.count', {
      org_id: id,
    });

    const trashes_req = transformExceedToPromise('org.risk.overview.trashes.count', {
      org_id: id,
    });

    Promise.all([operate_req, trashes_req])
      .then((results) => {
        const [operation_count, trashes_count] = results;
        dispatch(
          updateData({
            isLoadingOverviewCount: false,
            countInfo: {
              operation_count,
              trashes_count,
            },
          }),
        );
      })
      .catch(() => {
        dispatch(
          updateData({
            isLoadingOverviewCount: false,
          }),
        );
      });
  };
}

export function refreshOverviewScore() {
  return (dispatch) => {
    const dependency_req = transformExceedToPromise('org.risk.overview.score.calculate', {
      org_id: id,
    });

    dependency_req.then(() => {
      dispatch(getOverviewScore(false));
      dispatch(getAllCount());
    });
  };
}
